#include "dialog.h"
#include "ui_dialog.h"
#include "settingsdialog.h"
#include "ekadashicompdialog.h"
#include "computings.h"
#include "tithicompdialog.h"

#include <QDebug>
#include <QDesktopWidget>

const int sunTimeTimerDiscrete = 50; // мсек
const int tithiTimerDiscrete = 60*1000; // раз в минуту
//---------------------------------------------------------------------------------


Dialog::Dialog(QWidget *parent) :
    QDialog(parent,Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowSystemMenuHint |
            Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint),
    ui(new Ui::Dialog)
{
    qDebug() << "KaliYuga: " << GregorianToVedicKaliYuga(QDate::currentDate().year());
    qDebug() << "MahaYuga: " << GregorianToVedicMahaYuga(QDate::currentDate().year());
    qDebug() << "Manvantara: " << GregorianToVedicManvantara(QDate::currentDate().year());
    qDebug() << "Kalpa: " << GregorianToVedicKalpa(QDate::currentDate().year());
    qDebug() << "MahaKalpa: " << GregorianToVedicMahaKalpa(QDate::currentDate().year());

    ui->setupUi(this);

    connect(&mSunTimeTimer,SIGNAL(timeout()), this, SLOT(SuntimeChange()));
    connect(&mTithiTimer, SIGNAL(timeout()), this, SLOT(TithiTimeChange()));
    connect(ui->settingsPushButton,SIGNAL(clicked()), this, SLOT(showSettingsDialog()));

    if (false == Settings().LoadFile())
    {
        mSettings.SetDefaults();
        qDebug()<<tr("LoadSettingsFile Problem!");
    }

    // оформление окна-кнопки
    QRect g = QApplication::desktop()->availableGeometry(this);
    QPoint p(g.bottomRight().x() - 150, g.bottomRight().y() - 150);

    mPopup.setParent(QApplication::desktop());
    mPopup.setWindowFlags(Qt::FramelessWindowHint);
    mPopup.setGeometry(0,0,150,150);
    connect(&mPopup, SIGNAL(clicked()), this, SLOT(onPopupClicked()));
    mPopup.move(p);    
    //mPopup.show();

    // вывод информации о титхе
    TithiInfoOutput();

    // запуск таймеров
    mSunTimeTimer.start(sunTimeTimerDiscrete);
    mTithiTimer.start(tithiTimerDiscrete);    
}
//---------------------------

Dialog::~Dialog()
{   
   delete ui;
}
//---------------------------
//---------------------------------------------------------------------------------


void Dialog::SettingsChanged(CProgramSettings* s)
{
    mSettings = *s;    
    on_tithiReCompPushButton_clicked();
}
//---------------------------------------------------------------------------------


void Dialog::SuntimeChange()
{  
  QDateTime UTC;
  double lng;

  UTC = QDateTime::currentDateTimeUtc();
  lng = Settings().Lng();

  UTC = UTC.addSecs(qFloor(lng*SecsInLngDeg + 0.5));
  ui->relativeSunTimeEdit->setTime(UTC.time());

  UTC = UTC.addSecs(qFloor(TimeEquation(UTC.date().dayOfYear())*SecsInMin + 0.5));
  ui->trueSunTimeEdit->setTime(UTC.time());
}
//---------------------------

void Dialog::TithiTimeChange()
{
    TithiInfoOutput();
}
//---------------------------

void Dialog::showSettingsDialog()
{
    SettingsDialog d;
    CProgramSettings s;
    connect(&d, SIGNAL(ApplySettings(CProgramSettings*)), this, SLOT(SettingsChanged(CProgramSettings*)));

    if (QDialog::Accepted == d.exec())
    {        
        s = d.Settings();
        SettingsChanged(&s);
    }
}
//---------------------------

void Dialog::on_ekadashiCompPushButton_clicked()
{
    EkadashiCompDialog d;
    CProgramSettings s;
    s = Settings();
    d.setProgramSettings(s);
    d.exec();
}
//---------------------------

void Dialog::on_tithiCompPushButton_clicked()
{
    TithiCompDialog d;
    CProgramSettings s;
    s = Settings();
    d.setProgramSettings(s);
    d.exec();
}
//---------------------------

void Dialog::on_tithiReCompPushButton_clicked()
{
    TithiInfoOutput();
}
//---------------------------

void Dialog::onPopupClicked()
{
    mPopup.close();
}
//---------------------------
//---------------------------------------------------------------------------------


void Dialog::TithiInfoOutput()
{
    ui->tithiReCompPushButton->setDisabled(true);
    repaint();

    QCursor normCursor = cursor();
    setCursor(Qt::WaitCursor);

    // сейчас
    QString str;
    CTithi curTitha;    
    curTitha = SearchForCurrentTitha(Settings().TimeZone());
    static CTithi prevTitha = curTitha;

    str = curTitha.AsCurTithiStr();
    ui->tithiPlainTextEdit->setPlainText(str);

    // следующий экадаш
    QDateTime dt = QDateTime::currentDateTimeUtc(), dt2 = QDateTime::currentDateTimeUtc();
    QList<CTithi> ekadashi;

    dt2 = dt.addDays(30);
    ekadashi = SearchForEkadashi(dt,dt2,Settings().TimeZone());

    str = "Следующий экадаш";
    if (false == ekadashi.isEmpty())
    {
        str += " ";
        qint64 daysTo = QDate::currentDate().daysTo(ekadashi[0].dtBegin.date());
        if (0 == daysTo)
            str += "сегодня";
        else if (1 == daysTo)
            str += "завтра";
        str += "\n";
        str += ekadashi[0].AsEkadashStr();
    }

    ui->tithiPlainTextEdit->appendPlainText(str);

    setCursor(normCursor);
    ui->tithiReCompPushButton->setDisabled(false);

    QTextCursor textCursor = ui->tithiPlainTextEdit->textCursor();
    textCursor.movePosition(QTextCursor::Start);
    ui->tithiPlainTextEdit->setTextCursor(textCursor);

    // окно-кнопка с извещением
    if (mSettings.EkadashHint() && (false == mSettings.TithiHint()))
    {
        if ((curTitha.Num() != prevTitha.Num()) && curTitha.IsEkadash())
        {
            mPopup.setText("Экадаш начался");
            mPopup.show();
        }
        else if ((12 == curTitha.Num()) && prevTitha.IsEkadash())
        {
            mPopup.setText("Экадаш закончился");
            mPopup.show();
        }
    }
    else if (mSettings.TithiHint() && (false == mSettings.EkadashHint()))
    {
        if (curTitha.Num() != prevTitha.Num())
        {
            mPopup.setText("Титхи начались");
            mPopup.show();
        }
    }
    else if (mSettings.TithiHint() && mSettings.EkadashHint())
    {
        if ((curTitha.Num() != prevTitha.Num()) && curTitha.IsEkadash())
        {
            mPopup.setText("Экадаш начался");
            mPopup.show();
        }
        else if ((12 == curTitha.Num()) && prevTitha.IsEkadash())
        {
            mPopup.setText("Экадаш закончился");
            mPopup.show();
        }
        else if (curTitha.Num() != prevTitha.Num())
        {
            mPopup.setText("Титхи начались");
            mPopup.show();
        }
    }

    prevTitha = curTitha;    
}
//---------------------------
//---------------------------------------------------------------------------------
